﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 1/8/2010
 * Time: 3:54 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Microsoft.Win32;

namespace renmd5
{
	class Program
	{
		public static string GetMD5HashFromFile(string fileName)
		{
			FileStream file = new FileStream(fileName, FileMode.Open);
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] retVal = md5.ComputeHash(file);
			file.Close();

			StringBuilder s = new StringBuilder();
			foreach (byte b in retVal)
				s.Append(b.ToString("X2"));
			return s.ToString();
		}
		
		public static void ProcessFile(string file) {
			string md5 = GetMD5HashFromFile(file);
			string newPath = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar + md5;
			if (File.Exists(newPath)) {
				if (md5 == Path.GetFileName(file).ToUpper())
					return;
				File.Delete(newPath);
			}
			File.Move(file,	newPath);
		}
		
		public static void Main(string[] args)
		{
            if (args.Length == 0)
            {
                Console.WriteLine("usage:");
                Console.WriteLine("    renmd5.exe <dir_1|file_1> <dir_2|file_2> ... <dir_n|file_n>");
				Console.WriteLine();
				Console.WriteLine("1. Install");
				Console.WriteLine("2. Uninstall");
				Console.WriteLine();
				Console.WriteLine("Press any other key to exit");

				try
				{
					switch (Console.ReadKey(false).KeyChar)
					{
						case '1':
							RegistryKey key;
							key = Registry.ClassesRoot.CreateSubKey(@"*\shell\RenMD5\command");
							key.SetValue(null, @"renmd5.exe ""%1""");
							key.Close();
							key = Registry.ClassesRoot.CreateSubKey(@"Directory\shell\RenMD5\command");
							key.SetValue(null, @"renmd5.exe ""%1""");
							key.Close();
							break;
						case '2':
							Registry.ClassesRoot.DeleteSubKeyTree(@"*\shell\RenMD5");
							Registry.ClassesRoot.DeleteSubKeyTree(@"Directory\shell\RenMD5");
							break;
					}
					Console.WriteLine();
				}
				catch (Exception e)
				{
					Console.WriteLine();
					Console.WriteLine(e.Message);
				}
                return;
            }
			
			foreach(string dir in args) {
				if (File.Exists(dir))
				{
					ProcessFile(dir);
				}
				else if (Directory.Exists(dir))
				{
					string[] list = Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
					foreach (string file in list)
						ProcessFile(file);
				}
			}
			
		}
	}
}